<template>
  <div class="question-edit-container">
    <div class="page-header">
      <h1>编辑题目</h1>
      <div class="header-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </div>
    </div>
    
    <el-card v-loading="loading" class="form-card">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>
          
          <el-form-item label="题目标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入题目标题"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="题目类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择题目类型" @change="handleTypeChange">
                  <el-option label="单选题" value="single" />
                  <el-option label="多选题" value="multiple" />
                  <el-option label="判断题" value="judge" />
                  <el-option label="填空题" value="fill" />
                  <el-option label="简答题" value="essay" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="难度" prop="difficulty">
                <el-select v-model="form.difficulty" placeholder="请选择难度">
                  <el-option label="简单" value="easy" />
                  <el-option label="中等" value="medium" />
                  <el-option label="困难" value="hard" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="分值" prop="score">
                <el-input-number
                  v-model="form.score"
                  :min="1"
                  :max="100"
                  placeholder="请输入分值"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="科目" prop="subject">
                <el-input v-model="form.subject" placeholder="请输入科目" />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="标签">
                <el-input v-model="form.tags" placeholder="请输入标签，多个标签用逗号分隔" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 题目内容 -->
        <div class="form-section">
          <h3>题目内容</h3>
          
          <el-form-item label="题目描述" prop="content">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="4"
              placeholder="请输入题目描述"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
        </div>
        
        <!-- 选项设置 (单选题/多选题) -->
        <div v-if="['single', 'multiple'].includes(form.type)" class="form-section">
          <h3>选项设置</h3>
          
          <div v-for="(option, index) in form.options" :key="index" class="option-item">
            <el-form-item :label="`选项${String.fromCharCode(65 + index)}`" :prop="`options.${index}.content`">
              <div class="option-content">
                <el-input
                  v-model="option.content"
                  placeholder="请输入选项内容"
                  maxlength="200"
                />
                <el-checkbox
                  v-if="form.type === 'multiple'"
                  v-model="option.isCorrect"
                  class="correct-checkbox"
                >
                  正确答案
                </el-checkbox>
                <el-radio
                  v-else
                  v-model="correctAnswer"
                  :label="index"
                  class="correct-radio"
                >
                  正确答案
                </el-radio>
                <el-button
                  v-if="form.options.length > 2"
                  type="danger"
                  size="small"
                  text
                  @click="removeOption(index)"
                >
                  删除
                </el-button>
              </div>
            </el-form-item>
          </div>
          
          <el-button
            v-if="form.options.length < 6"
            type="primary"
            text
            @click="addOption"
          >
            <el-icon><Plus /></el-icon>
            添加选项
          </el-button>
        </div>
        
        <!-- 判断题答案 -->
        <div v-if="form.type === 'judge'" class="form-section">
          <h3>正确答案</h3>
          
          <el-form-item label="答案" prop="judgeAnswer">
            <el-radio-group v-model="form.judgeAnswer">
              <el-radio :label="true">正确</el-radio>
              <el-radio :label="false">错误</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        
        <!-- 填空题/简答题答案 -->
        <div v-if="['fill', 'essay'].includes(form.type)" class="form-section">
          <h3>参考答案</h3>
          
          <el-form-item label="答案" prop="textAnswer">
            <el-input
              v-model="form.textAnswer"
              type="textarea"
              :rows="4"
              placeholder="请输入参考答案"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
        </div>
        
        <!-- 解析 -->
        <div class="form-section">
          <h3>题目解析</h3>
          
          <el-form-item label="解析">
            <el-input
              v-model="form.explanation"
              type="textarea"
              :rows="3"
              placeholder="请输入题目解析（可选）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const loading = ref(false)
const saving = ref(false)

const form = reactive({
  id: null,
  title: '',
  type: '',
  difficulty: '',
  score: 5,
  subject: '',
  tags: '',
  content: '',
  options: [
    { content: '', isCorrect: false },
    { content: '', isCorrect: false }
  ],
  judgeAnswer: null,
  textAnswer: '',
  explanation: ''
})

const correctAnswer = ref(0)

const rules = {
  title: [
    { required: true, message: '请输入题目标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分值', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请输入科目', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入题目描述', trigger: 'blur' }
  ],
  judgeAnswer: [
    { required: true, message: '请选择正确答案', trigger: 'change' }
  ],
  textAnswer: [
    { required: true, message: '请输入参考答案', trigger: 'blur' }
  ]
}

// 监听题目类型变化
const handleTypeChange = (type) => {
  if (['single', 'multiple'].includes(type)) {
    if (form.options.length === 0) {
      form.options = [
        { content: '', isCorrect: false },
        { content: '', isCorrect: false }
      ]
    }
  }
}

// 添加选项
const addOption = () => {
  if (form.options.length < 6) {
    form.options.push({ content: '', isCorrect: false })
  }
}

// 删除选项
const removeOption = (index) => {
  if (form.options.length > 2) {
    form.options.splice(index, 1)
    // 如果删除的是当前正确答案，重置正确答案
    if (form.type === 'single' && correctAnswer.value >= form.options.length) {
      correctAnswer.value = 0
    }
  }
}

// 监听单选题正确答案变化
watch(correctAnswer, (newVal) => {
  if (form.type === 'single') {
    form.options.forEach((option, index) => {
      option.isCorrect = index === newVal
    })
  }
})

// 加载题目数据
const loadQuestion = async () => {
  const questionId = route.params.id
  if (!questionId) {
    ElMessage.error('题目ID不存在')
    router.push('/questions')
    return
  }
  
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    const mockData = {
      id: questionId,
      title: '以下哪个是Vue.js的核心特性？',
      type: 'single',
      difficulty: 'easy',
      score: 5,
      subject: '前端开发',
      tags: 'Vue.js,前端框架',
      content: '请选择Vue.js的核心特性',
      options: [
        { content: '响应式数据绑定', isCorrect: true },
        { content: '虚拟DOM', isCorrect: false },
        { content: '组件化开发', isCorrect: false },
        { content: '以上都是', isCorrect: false }
      ],
      judgeAnswer: null,
      textAnswer: '',
      explanation: 'Vue.js的核心特性包括响应式数据绑定、虚拟DOM和组件化开发等。'
    }
    
    Object.assign(form, mockData)
    
    // 设置单选题正确答案
    if (form.type === 'single') {
      const correctIndex = form.options.findIndex(option => option.isCorrect)
      if (correctIndex !== -1) {
        correctAnswer.value = correctIndex
      }
    }
    
  } catch (error) {
    ElMessage.error('加载题目数据失败')
    router.push('/questions')
  } finally {
    loading.value = false
  }
}

// 保存题目
const handleSave = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        // 验证选择题选项
        if (['single', 'multiple'].includes(form.type)) {
          const hasEmptyOption = form.options.some(option => !option.content.trim())
          if (hasEmptyOption) {
            ElMessage.error('请填写所有选项内容')
            return
          }
          
          const hasCorrectAnswer = form.options.some(option => option.isCorrect)
          if (!hasCorrectAnswer) {
            ElMessage.error('请设置正确答案')
            return
          }
        }
        
        // 模拟保存API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success('题目更新成功')
        router.push('/questions')
      } catch (error) {
        ElMessage.error('更新失败，请重试')
      } finally {
        saving.value = false
      }
    }
  })
}

// 取消
const handleCancel = () => {
  router.back()
}

onMounted(() => {
  loadQuestion()
})
</script>

<style scoped>
.question-edit-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.form-section h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.option-item {
  margin-bottom: 15px;
}

.option-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.option-content .el-input {
  flex: 1;
}

.correct-checkbox,
.correct-radio {
  white-space: nowrap;
}
</style>